28
PROGRAM TO CONVERT INFIX NOTATION TO POSTFIX
NOTATION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_EXPRESSION_LENGTH 100
// Function to check if a character is an operator
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');
}
// Function to get the precedence of an operator
int getPrecedence(char op) {
if (op == '^') return 3;
else if (op == '*' || op == '/') return 2;
else if (op == '+' || op == '-') return 1;
return 0; // Lowest precedence
}
// Function to convert infix expression to postfix expression
void infixToPostfix(char infix[], char postfix[]) {
int i, j;
char stack[MAX_EXPRESSION_LENGTH];
int top = -1;
for (i = 0, j = 0; i < strlen(infix); i++) {
char ch = infix[i];
if (isalnum(ch)) {
postfix[j++] = ch;
} else if (ch == '(') {
stack[++top] = ch;
} else if (ch == ')') {
while (top >= 0 && stack[top] != '(') {
postfix[j++] = stack[top--];
}
if (top >= 0 && stack[top] == '(') {
top--; // Pop '(' from the stack
}
} else if (isOperator(ch)) {
while (top >= 0 && getPrecedence(ch) <= getPrecedence(stack[top])) {
postfix[j++] = stack[top--];
}